package com.example.xcService.pojo.channels.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.xcService.pojo.channels.ChannelResult;
import com.example.xcService.pojo.channels.ChannelService;
import com.example.xcService.pojo.tool.HttpTool;
import com.example.xcService.pojo.tool.RSATool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 饿了么官方接口
 * **/
@Slf4j
public class Plugin_ECARD_P013 implements ChannelService {
    public ChannelResult QueryBalance(JSONObject apiConfig){
        System.out.println("成功调用了QueryBalance");
        return  ChannelResult.success("success");
    }
    public  ChannelResult Submit(JSONObject apiConfig, Map<String,Object> data){

        try {

            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            String timestamp=String.valueOf(System.currentTimeMillis());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("welfareCaseNo", dataConfig.getString("SUPProductId"));
            jsonObject.put("mobile", dataConfig.getString("AccountVal"));
            jsonObject.put("outTradeNo", dataConfig.getString("ChannelOrderCode"));

            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("partnerId",  apiConfig.getString("USERID"));
            dataParams.put("timestamp", timestamp);
            dataParams.put("reqId", timestamp);
            dataParams.put("data", RSATool.encrypt(JSONObject.toJSONString(jsonObject),apiConfig.getString("SecretKey")));

            String signStr=getSignStr(dataParams);
            dataParams.put("sign",RSATool.sign(signStr.getBytes("UTF-8"),apiConfig.getString("PrivateKey")));

            String url=apiConfig.getString("SubmitURL");

            String responseContent = HttpTool.sendPost(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("respCode");
            String msg = retobj.getString("message");
            if (code.equals("0000") || code.equals("3101")) {
                return ChannelResult.IN_PROCESS("充值中");
            }
            else if (code.equals("4000") || code.equals("40001")){
                return ChannelResult.error("系统异常,请幂等重试,重新提交订单");
            }
            else {
                return ChannelResult.FAILED(code+","+msg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("饿了么提交订单接口错误：",ex);
            return  ChannelResult.error("饿了么提交订单接口错误");
        }
    }

    public  ChannelResult Query(JSONObject apiConfig,Map<String,Object> data) {
        try {

            JSONObject dataConfig= JSONObject.parseObject(JSONObject.toJSONString(data));

            String timestamp=String.valueOf(System.currentTimeMillis());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("outTradeNo", dataConfig.getString("ChannelOrderCode"));



            Map dataParams = new LinkedHashMap<String, String>();
            dataParams.put("partnerId",  apiConfig.getString("USERID"));
            dataParams.put("timestamp", timestamp);
            dataParams.put("reqId", timestamp);
            dataParams.put("data", RSATool.encrypt(JSONObject.toJSONString(jsonObject),apiConfig.getString("SecretKey")));

            String signStr=getSignStr(dataParams);
            dataParams.put("sign",RSATool.sign(signStr.getBytes("UTF-8"),apiConfig.getString("PrivateKey")));

            String url=apiConfig.getString("QueryURL");

            String responseContent = HttpTool.sendPost(url, dataParams);
            JSONObject retobj = JSONObject.parseObject(responseContent);

            String code = retobj.getString("respCode");
            String msg = retobj.getString("message");
            if (code.equals("0000")) {

                JSONObject orderData=JSONObject.parseObject(RSATool.decrypt(retobj.getString("data"),apiConfig.getString("PrivateKey")));
                String status=orderData.getString("applyResult");
                if ("processed".equals(status))
                {
                    String grantResult = orderData.getJSONArray("detail").getJSONObject(0).getString("grantResult");
                    if ("granted".equals(grantResult))
                    {
                        return ChannelResult.success("充值成功");
                    }else if("grantFaild".equals(grantResult))
                    {
                        return ChannelResult.FAILED("充值失败");
                    }

                }
                else if ("faild".equals(status))
                {
                    return ChannelResult.FAILED("充值失败");
                }
                else if ( "accepted".equals(status))
                {
                    return ChannelResult.IN_PROCESS("充值中");
                }
                return ChannelResult.error(status);
            }
            else {
                return ChannelResult.error(code+msg);
            }
        }catch (Exception ex){
            ex.printStackTrace();
            log.error("饿了么查询订单接口错误：",ex);
            return  ChannelResult.error("饿了么查询订单接口错误");
        }
    }


    public  ChannelResult Notify(JSONObject apiConfig,Map<String,Object> data){
        System.out.println("成功调用了Notify");
        return  ChannelResult.success("success");

    }

    public static String getSignStr(Map<String, String> map) {
        String result = "";
        try {
            List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
            // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）
            Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {

                public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                    return (o1.getKey()).toString().compareTo(o2.getKey());
                }
            });
            // 构造签名键值对的格式
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, String> item : infoIds) {
                if (item.getKey() != null && item.getKey() != "") {
                    String key = String.valueOf(item.getKey());
                    String val = String.valueOf(item.getValue());
                    if(sb.length()>0){
                        sb.append("&");
                    }
                    if (StringUtils.hasLength(val)) {
                        sb.append(key +"="+ val);
                    }
                }
            }
            result = sb.toString();
        } catch (Exception e) {
            log.error("获取签名明文出错：", e);
            return null;
        }
        return result;
    }
}
